package algorithm.leetcode.array;

/**
 * @auther zhouliangliang
 * @date 2022/10/9 10:34
 * @description  螺旋填充数组
 * 给定一个N * N的数组, 从1开始顺时针螺旋填充数组
 */
public class GenerateMetrix {
    //螺旋填充数组
    public int[][] generateMatrix(int n) {
        int left = 0;
        int right = n-1;
        int top = 0;
        int bottom = n-1;
        int start = 1;
        int max = n * n;
        int[][] matrix = new int[n][n];
        while(start <= max) {
            //从左到右填充上边的行，行不变，列递增
            for(int i=left; i<=right; i++) {
                matrix[top][i] = start ++;
            }
            top = top + 1;//填充过一行了

            //从上到下填充右边的列，列不变，行递增
            for(int i=top; i<=bottom; i++) {
                matrix[i][right] = start ++;
            }
            right = right -1;//填充过右侧列了

            //从右到左填充下边的行，行不变，列递减
            for(int i=right; i>=left; i--) {
                matrix[bottom][i] = start++;
            }
            bottom = bottom - 1;//填充过下侧行了

            //从下到上填充左侧的列，列不变，行递减
            for(int i=bottom; i>=top; i--) {
                matrix[i][left] = start++;
            }
            left = left + 1;
        }
        return matrix;
    }

    private void show(int[][] matrix) {
        for(int i=0; i<matrix.length; i++) {
            for(int j=0; j<matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        GenerateMetrix gm = new GenerateMetrix();
        int[][] array = gm.generateMatrix(10);
        gm.show(array);
    }
}
